
package jpoco.io;

import java.lang.reflect.Type;

import jpoco.client.Format;
import jpoco.client.Response;
import jpoco.internal.gson.GsonFactory;
import jpoco.internal.xstream.XStreamFactory;

import com.google.gson.Gson;
import com.thoughtworks.xstream.XStream;


/**
 *
 * 
 * @see Serializer
 * 
 * @author Sean C. Sullivan
 *
 *
 *
 */
public class Deserializer
{
	protected XStream xstream;
	protected Gson gson;
	protected Format format;
	
	public Deserializer(Format fmt, Class<? extends Response> clazz)
	{
		this.format = fmt;
		
		if (this.format == Format.XML)
		{
			xstream = XStreamFactory.createXStream(this.format, clazz);
		}
		else if (this.format == Format.JSON)
		{
			gson = GsonFactory.createGson();
		}
		else
		{
			throw new RuntimeException("unexpected format: " + this.format);
		}
	}
	

	public <T extends Response> T deserialize(java.io.InputStream input, Class<? extends Response> responseClass)
	{
		Response r = (Response) xstream.fromXML(input);
		
		return (T) r;
	}
	
	public <T extends Response> T deserialize(String s, Class<? extends Response> clazz)
	{
		Response r;
		
		if (format == Format.JSON)
		{
			r = gson.fromJson(s, clazz);
		}
		else
		{
			r = (Response) xstream.fromXML(s);
		}
		
		r.setFormat(this.format);
		
		return (T) r;
	}
	
}
